import CryptoJs from 'crypto-js';
self.onmessage = function (event) {
  const file = event.data.file;
  const chunkSize = event.data.chunkSize || 1024 * 1024;
  const hashAlgorithm = event.data.hashAlgorithm || 'MD5';

  const fileReader = new FileReader();
  let offset = 0;
  let hash = CryptoJs.algo[hashAlgorithm].create();

  fileReader.onload = function (e) {
    const chunk = e.target.result;
    const wordArray = CryptoJs.lib.WordArray.create(chunk);
    hash.update(wordArray);

    offset += chunk.byteLength;
    if (offset < file.size) {
      readNextChunk();
    } else {
      const finalHash = hash.finalize();
      self.postMessage({ hash: finalHash.toString(CryptoJs.enc.Hex) });
    }
  };

  fileReader.onerror = function (e) {
    self.postMessage({ error: e.target.error });
  };

  function readNextChunk() {
    const slice = file.slice(offset, offset + chunkSize);
    fileReader.readAsArrayBuffer(slice);
  }

  readNextChunk();
};
